﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace YeaTrip.Framework.CookieSession
{
    /// <summary>
    /// Cookie类型枚举
    /// </summary>
    public enum CookieEnum
    {
        LoginAccount = 0,  //登录账号
        CustName        //客户姓名
    }

    /// <summary>
    /// Cookie操作类
    /// </summary>
    public class YeaTripCookie
    {
        private HttpResponseBase httpResponseBase;
        private HttpResponse httpResponse;
        private HttpRequestBase httpRequestBase;
        private HttpRequest httpRequest;

        public YeaTripCookie(HttpResponseBase Response, HttpRequestBase Request)
        {
            httpResponseBase = Response;
            httpResponse = null;
            httpRequestBase = Request;
            httpRequest = null;
        }

        public YeaTripCookie(HttpResponse Response, HttpRequest Request)
        {
            httpResponse = Response;
            httpResponseBase = null;
            httpRequest = Request;
            httpRequestBase = null;
        }

        /// <summary>
        /// 设置Cookie
        /// </summary>
        /// <param name="cookie">Cookie名称</param>
        /// <param name="value">Cookie值</param>
        public void SetCookie(CookieEnum cookie, string value)
        {
            string cookieName = cookie.ToString();
            //从配置文件中读取Cookie的过期时间
            int expireDay = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["CookieExpiresSpan"]);

            HttpCookie _cookie;
            if (httpResponseBase != null)
            {
                _cookie = httpResponseBase.Cookies[cookieName];
            }
            else
            {
                _cookie = httpResponse.Cookies[cookieName];
            }

            if (_cookie == null)
            {
                _cookie = new HttpCookie(cookieName);
            }

            _cookie.Expires = DateTime.Now.AddDays(expireDay);
            _cookie.Value = value;

            if (httpResponseBase != null)
            {
                httpResponseBase.SetCookie(_cookie);
            }
            else
            {
                httpResponse.SetCookie(_cookie);
            }
        }
    }
}
